package com.codingvip.concurrent;

import java.util.concurrent.CountDownLatch;
 
public class CountDownLatchDemo {
 
    public static void main(String[] args) {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch doneLatch = new CountDownLatch(3);
        for(int i = 0; i < 3; i++) {
            new Thread(new Worker(startLatch, doneLatch)).start();;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Main thread - Doing setup");
        //Signal from main thread for other threads to start
        startLatch.countDown();
        try {
            // Main thread waiting for other threads to finish
            doneLatch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Main thread - Proceed after all the threads are done");
    }
 
}
 
class Worker implements Runnable{
    private final CountDownLatch startLatch;
    private final CountDownLatch doneLatch;
    Worker(CountDownLatch startLatch, CountDownLatch doneLatch) {
        this.startLatch = startLatch;
        this.doneLatch = doneLatch;
    }
    @Override
    public void run() {
        try {
            System.out.println("Calling await ...");
            // don't start until set up is done
            startLatch.await();
            System.out.println("Doing processing " + Thread.currentThread().getName());
            doneLatch.countDown();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}